from vnpy.trader.optimize import OptimizationSetting
from vnpy_ctastrategy.backtesting import BacktestingEngine
from vnpy.trader.constant import Interval
from datetime import datetime
import sys
from pathlib import Path
# 获取项目根目录路径
project_root = Path(__file__).parent.parent.parent  # 根据实际层级调整
sys.path.append(str(project_root))


from examples.strategies.MomentumReversalStrategy  import MomentumReversalStrategy

def optimize_parameters():
    """策略参数优化"""
    engine = BacktestingEngine()
    engine.set_parameters(
        vt_symbol="832566.BSE",
        interval=Interval.DAILY,
        start=datetime(2025, 1, 1),
        end=datetime(2025, 8, 15),
        rate=0.3/10000,
        slippage=0.2,
        size=10,
        pricetick=0.2,
        capital=1_000_000,
    )
    
    # 设置优化参数
    # setting = OptimizationSetting()
    # setting.set_target("sharpe_ratio")  # 优化目标：夏普比率
    
    # # 添加优化参数范围
    # setting.add_parameter("holding_days", 5, 10, 1)    # 从3到10，步长1
    # setting.add_parameter("position_ratio", 0.2, 0.5, 0.1)   # 从15到30，步长1
    
    # 生成优化设置对象（不是策略类）
    optimization_setting = MomentumReversalStrategy.generate_settings("sharpe_ratio")
    optimization_setting.set_target("sharpe_ratio")
    #optimization_setting.add_parameter("target_name", "sharpe_ratio")    # 从3到10，步长1
    
    # 运行优化
    result = engine.run_optimization(
        MomentumReversalStrategy,
        optimization_setting,
        True
    )
    
    print("优化结果:")
    for i, (params, value) in enumerate(result):
        print(f"{i+1}. 参数: {params}, 夏普比率: {value:.3f}")
    
    return result

if __name__ == "__main__":
    optimize_parameters()